/** @file
  Pci Hotplug Driver : This file will perform specific PCI-EXPRESS
  Devics resource configuration.

 @copyright
  INTEL CONFIDENTIAL
  Copyright 2006 - 2017 Intel Corporation.

  The source code contained or described herein and all documents related to the
  source code ("Material") are owned by Intel Corporation or its suppliers or
  licensors. Title to the Material remains with Intel Corporation or its suppliers
  and licensors. The Material may contain trade secrets and proprietary and
  confidential information of Intel Corporation and its suppliers and licensors,
  and is protected by worldwide copyright and trade secret laws and treaty
  provisions. No part of the Material may be used, copied, reproduced, modified,
  published, uploaded, posted, transmitted, distributed, or disclosed in any way
  without Intel's prior express written permission.

  No license under any patent, copyright, trade secret or other intellectual
  property right is granted to or conferred upon you by disclosure or delivery
  of the Materials, either expressly, by implication, inducement, estoppel or
  otherwise. Any license under such intellectual property rights must be
  express and approved by Intel in writing.

  Unless otherwise agreed by Intel in writing, you may not remove or alter
  this notice or any other notice embedded in Materials by Intel or
  Intel's suppliers or licensors in any way.

  This file contains a 'Sample Driver' and is licensed as such under the terms
  of your license agreement with Intel or your vendor. This file may be modified
  by the user, subject to the additional terms of the license agreement.

@par Specification Reference:
**/

//
// Statements that include other files
//
#include "PciHotPlug.h"

#include <TbtBoardInfo.h>
#include <Library/PchPcieRpLib.h>

#define PCIE_NUM  (20)
#define PEG_NUM   (3)
#define PADDING_BUS (1)
#define PADDING_NONPREFETCH_MEM (1)
#define PADDING_PREFETCH_MEM (1)
#define PADDING_IO (1)
#define PADDING_NUM (PADDING_BUS + PADDING_NONPREFETCH_MEM + PADDING_PREFETCH_MEM + PADDING_IO)

GLOBAL_REMOVE_IF_UNREFERENCED EFI_HPC_LOCATION          mPcieLocation[PCIE_NUM + PEG_NUM];

GLOBAL_REMOVE_IF_UNREFERENCED UINTN mHpcCount = 0;

GLOBAL_REMOVE_IF_UNREFERENCED PCIE_HOT_PLUG_DEVICE_PATH mHotplugPcieDevicePathTemplate = {
  ACPI,
  PCI(0xFF, 0xFF), // Dummy Device no & Function no
  END
};

/**
  Entry point for the driver.

  This routine reads the PlatformType GPI on FWH and produces a protocol
  to be consumed by the chipset driver to effect those settings.

  @param[in]  ImageHandle    An image handle.
  @param[in]  SystemTable    A pointer to the system table.

  @retval     EFI_SUCCESS.
**/
EFI_STATUS
EFIAPI
PciHotPlug (
  IN EFI_HANDLE                   ImageHandle,
  IN EFI_SYSTEM_TABLE             *SystemTable
  )
{
  EFI_STATUS                       Status;
  PCI_HOT_PLUG_INSTANCE            *PciHotPlug;
  SA_POLICY_PROTOCOL               *SaPolicy;
  UINTN                            Index;
  UINTN                            RpDev;
  UINTN                            RpFunc;
  PCIE_HOT_PLUG_DEVICE_PATH        *HotplugPcieDevicePath;
  UINTN                            VariableSize;
  PCH_SETUP                        PchSetup;
  PCIE_DXE_CONFIG                  *PcieDxeConfig;
  UINT32                           PcieRootPortHpeData;

  VariableSize = sizeof (PCH_SETUP);
  Status = gRT->GetVariable (
                  L"PchSetup",
                  &gPchSetupVariableGuid,
                  NULL,
                  &VariableSize,
                  &PchSetup
                  );
  ASSERT_EFI_ERROR (Status);

  PcieRootPortHpeData = PcdGet32 (PcdPchPcieRootPortHpe);
  //
  // PCH Rootports Hotplug device path creation
  //
  for (Index = 0; Index < PCIE_NUM; Index++) {
    if (((PcieRootPortHpeData >> Index) & BIT0) == BIT0) { // Check the Rootport no's hotplug is set
      Status = GetPchPcieRpDevFun (Index, &RpDev, &RpFunc); // Get the actual device/function no corresponding to the Rootport no provided
      ASSERT_EFI_ERROR (Status);

      HotplugPcieDevicePath = NULL;
      HotplugPcieDevicePath = AllocatePool (sizeof (PCIE_HOT_PLUG_DEVICE_PATH));
      ASSERT (HotplugPcieDevicePath != NULL);
      if (HotplugPcieDevicePath == NULL) {
        return EFI_OUT_OF_RESOURCES;
      }
      CopyMem (HotplugPcieDevicePath, &mHotplugPcieDevicePathTemplate, sizeof (PCIE_HOT_PLUG_DEVICE_PATH));
      HotplugPcieDevicePath->PciRootPortNode.Device = (UINT8) RpDev; // Update real Device no
      HotplugPcieDevicePath->PciRootPortNode.Function = (UINT8) RpFunc; // Update real Function no

      mPcieLocation[mHpcCount].HpcDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)HotplugPcieDevicePath;
      mPcieLocation[mHpcCount].HpbDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)HotplugPcieDevicePath;
      mHpcCount++;

      DEBUG ((DEBUG_INFO, "(%02d) PciHotPlug (PCH RP#) : Bus 0x00, Device 0x%x, Function 0x%x is added to the Hotplug Device Path list \n", mHpcCount, RpDev, RpFunc));
    }
  }

  Status = gBS->LocateProtocol (
                  &gSaPolicyProtocolGuid,
                  NULL,
                  (VOID**) &SaPolicy
                  );
  ASSERT_EFI_ERROR (Status);

  Status = GetConfigBlock ((VOID *)SaPolicy, &gPcieDxeConfigGuid, (VOID *)&PcieDxeConfig);
  ASSERT_EFI_ERROR (Status);

  //
  // PEG Rootports Hotplug device path creation
  //
  for (Index = PCIE_NUM; Index < (PCIE_NUM + PEG_NUM); Index++) {
    if (PcieDxeConfig->PegRootPortHPE[Index-PCIE_NUM]) { // Check the Rootport no's hotplug is set
      RpDev = SA_PEG_DEV_NUM;
      RpFunc = (Index-PCIE_NUM);

      HotplugPcieDevicePath = NULL;
      HotplugPcieDevicePath = AllocatePool (sizeof (PCIE_HOT_PLUG_DEVICE_PATH));
      ASSERT (HotplugPcieDevicePath != NULL);
      if (HotplugPcieDevicePath == NULL) {
        return EFI_OUT_OF_RESOURCES;
      }
      CopyMem (HotplugPcieDevicePath, &mHotplugPcieDevicePathTemplate, sizeof (PCIE_HOT_PLUG_DEVICE_PATH));
      HotplugPcieDevicePath->PciRootPortNode.Device = (UINT8) RpDev; // Update real Device no
      HotplugPcieDevicePath->PciRootPortNode.Function = (UINT8) RpFunc; // Update real Function no

      mPcieLocation[mHpcCount].HpcDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)HotplugPcieDevicePath;
      mPcieLocation[mHpcCount].HpbDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)HotplugPcieDevicePath;
      mHpcCount++;

      DEBUG ((DEBUG_INFO, "(%02d) PciHotPlug (PEG RP#) : Bus 0x00, Device 0x%x, Function 0x%x is added to the Hotplug Device Path list \n", mHpcCount, RpDev, RpFunc));
    }
  }

  PciHotPlug = AllocatePool (sizeof (PCI_HOT_PLUG_INSTANCE));
  ASSERT (PciHotPlug != NULL);
  if (PciHotPlug == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  //
  // Initialize driver private data.
  //
  ZeroMem (PciHotPlug, sizeof (PCI_HOT_PLUG_INSTANCE));

  PciHotPlug->Signature                               = PCI_HOT_PLUG_DRIVER_PRIVATE_SIGNATURE;
  PciHotPlug->HotPlugInitProtocol.GetRootHpcList      = GetRootHpcList;
  PciHotPlug->HotPlugInitProtocol.InitializeRootHpc   = InitializeRootHpc;
  PciHotPlug->HotPlugInitProtocol.GetResourcePadding  = GetResourcePadding;

  Status = gBS->InstallProtocolInterface (
                  &PciHotPlug->Handle,
                  &gEfiPciHotPlugInitProtocolGuid,
                  EFI_NATIVE_INTERFACE,
                  &PciHotPlug->HotPlugInitProtocol
                  );
  ASSERT_EFI_ERROR (Status);

  return EFI_SUCCESS;
}


/**
  This procedure returns a list of Root Hot Plug controllers that require
  initialization during boot process

  @param[in]  This      The pointer to the instance of the EFI_PCI_HOT_PLUG_INIT protocol.
  @param[out] HpcCount  The number of Root HPCs returned.
  @param[out] HpcList   The list of Root HPCs. HpcCount defines the number of elements in this list.

  @retval EFI_SUCCESS.
**/
EFI_STATUS
EFIAPI
GetRootHpcList (
  IN EFI_PCI_HOT_PLUG_INIT_PROTOCOL    *This,
  OUT UINTN                            *HpcCount,
  OUT EFI_HPC_LOCATION                 **HpcList
  )
{
  *HpcCount = mHpcCount;
  *HpcList  = mPcieLocation;

  return EFI_SUCCESS;
}


/**
  This procedure Initializes one Root Hot Plug Controller
  This process may casue initialization of its subordinate buses

  @param[in]  This            The pointer to the instance of the EFI_PCI_HOT_PLUG_INIT protocol.
  @param[in]  HpcDevicePath   The Device Path to the HPC that is being initialized.
  @param[in]  HpcPciAddress   The address of the Hot Plug Controller function on the PCI bus.
  @param[in]  Event           The event that should be signaled when the Hot Plug Controller initialization is complete. Set to NULL if the caller wants to wait until the entire initialization process is complete. The event must be of the type EFI_EVT_SIGNAL.
  @param[out] HpcState        The state of the Hot Plug Controller hardware. The type EFI_Hpc_STATE is defined in section 3.1.

  @retval   EFI_SUCCESS.
**/
EFI_STATUS
EFIAPI
InitializeRootHpc (
  IN  EFI_PCI_HOT_PLUG_INIT_PROTOCOL      *This,
  IN  EFI_DEVICE_PATH_PROTOCOL            *HpcDevicePath,
  IN  UINT64                              HpcPciAddress,
  IN  EFI_EVENT                           Event, OPTIONAL
  OUT EFI_HPC_STATE                       *HpcState
  )
{
  if (Event) {
    gBS->SignalEvent (Event);
  }

  *HpcState = EFI_HPC_STATE_INITIALIZED;

  return EFI_SUCCESS;
}


/**
  Selects the proper TBT Root port to assign resources
  based on the user input value

  @param[in]  SetupData          Pointer to Setup data

  @retval     TbtSelectorChosen  Rootport number.
**/
BOOLEAN
GetRootporttoSetResourcesforTbt (
  IN SETUP_DATA *SetupData,
  IN UINTN RpIndex
  )
{
  TBT_INFO_HOB             *gTbtInfoHob = NULL;
  EFI_STATUS               Status;
  DEBUG ((DEBUG_INFO, "GetRootporttoSetResourcesforTbt \n"));
  if (SetupData->TbtSelector != 0) {
    DEBUG ((DEBUG_INFO, "TbtSelectorChosen is based on setup \n"));
    if (RpIndex == SetupData->TbtSelector - 1) {
      return(TRUE);
    }
    if ((1 == SetupData->Multicontroller) && (RpIndex == SetupData->TbtSelector1 - 1)) {
      return(TRUE);
    }
  }
  else {
    Status = EfiGetSystemConfigurationTable (&gEfiHobListGuid, (VOID **) &gTbtInfoHob);
    if (!EFI_ERROR (Status)) {
      gTbtInfoHob = GetNextGuidHob (&gTbtInfoHobGuid, gTbtInfoHob);
    }
    if (gTbtInfoHob != NULL) {
      DEBUG ((DEBUG_INFO, "TbtSelectorChosen is based on default selector \n"));
      if(RpIndex == gTbtInfoHob->TbtDefaultSelectorInfo - 1) {
        return(TRUE);
      }
      if((1 == SetupData->Multicontroller) && (RpIndex == gTbtInfoHob->TbtDefaultSelectorInfo1 - 1)) {
        return(TRUE);
      }
    }
  }
  return (FALSE);
}


/**
  Returns the resource padding required by the PCI bus that is controlled by the specified Hot Plug Controller.

  @param[in]  This           The pointer to the instance of the EFI_PCI_HOT_PLUG_INIT protocol. initialized.
  @param[in]  HpcDevicePath  The Device Path to the Hot Plug Controller.
  @param[in]  HpcPciAddress  The address of the Hot Plug Controller function on the PCI bus.
  @param[out] HpcState       The state of the Hot Plug Controller hardware. The type EFI_HPC_STATE is defined in section 3.1.
  @param[out] Padding        This is the amount of resource padding required by the PCI bus under the control of the specified Hpc. Since the caller does not know the size of this buffer, this buffer is allocated by the callee and freed by the caller.
  @param[out] Attribute      Describes how padding is accounted for.

  @retval     EFI_SUCCESS.
**/
EFI_STATUS
EFIAPI
GetResourcePadding (
  IN  EFI_PCI_HOT_PLUG_INIT_PROTOCOL  *This,
  IN  EFI_DEVICE_PATH_PROTOCOL        *HpcDevicePath,
  IN  UINT64                          HpcPciAddress,
  OUT EFI_HPC_STATE                   *HpcState,
  OUT VOID                            **Padding,
  OUT EFI_HPC_PADDING_ATTRIBUTES      *Attributes
  )
{
  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *PaddingResource;
  EFI_STATUS                        Status;
  EFI_STATUS                        Status2;
  EFI_STATUS                        Status3;
  UINT8                             RsvdExtraBusNum = 0;
  UINT16                            RsvdPcieMegaMem = 10;
  UINT8                             PcieMemAddrRngMax = 0;
  UINT16                            RsvdPciePMegaMem = 10;
  UINT8                             PciePMemAddrRngMax = 0;
  SA_SETUP                          SaSetup;
  PCH_SETUP                         PchSetup;
  SETUP_DATA                        SetupData;
  UINTN                             VariableSize;
  UINT8                             RsvdPcieKiloIo = 4;
  BOOLEAN                           SetResourceforTbt = FALSE;
  UINTN                             RpIndex;
  UINTN                             RpDev;
  UINTN                             RpFunc;

  PaddingResource = AllocatePool (PADDING_NUM * sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR));
  ASSERT (PaddingResource != NULL);
  if (PaddingResource == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  *Padding = (VOID *) PaddingResource;

  //
  // Check if PCIe Root Hob Controller need to reserve bus for docking downstream P2P hotplug
  //
  VariableSize = sizeof(SETUP_DATA);
  Status = gRT->GetVariable(
                  L"Setup",
                  &gSetupVariableGuid,
                  NULL,
                  &VariableSize,
                  &SetupData
                  );

  VariableSize = sizeof(SA_SETUP);
  Status2 = gRT->GetVariable(
                  L"SaSetup",
                  &gSaSetupVariableGuid,
                  NULL,
                  &VariableSize,
                  &SaSetup
                  );

  VariableSize = sizeof (PCH_SETUP);
  Status3 = gRT->GetVariable (
                  L"PchSetup",
                  &gPchSetupVariableGuid,
                  NULL,
                  &VariableSize,
                  &PchSetup
                  );

  RpDev = (UINTN) ((HpcPciAddress >> 16) & 0xFF);
  RpFunc = (UINTN) ((HpcPciAddress >> 8) & 0xFF);

  // Get the actual Rootport no corresponding to the device/function no provided
  if (RpDev == SA_PEG_DEV_NUM) {
    // PEG
    RpIndex = PCIE_NUM + RpFunc;
    DEBUG ((DEBUG_INFO, "GetResourcePadding : PEG Rootport no %02d Bus 0x00, Device 0x%x, Function 0x%x \n", (RpIndex-PCIE_NUM), RpDev, RpFunc));
  } else {
    // PCH
    Status = GetPchPcieRpNumber (RpDev, RpFunc, &RpIndex);
    DEBUG ((DEBUG_INFO, "GetResourcePadding : PCH Rootport no %02d Bus 0x00, Device 0x%x, Function 0x%x \n", RpIndex, RpDev, RpFunc));
  }

  if ((PcdGetBool (PcdTbtSupport)) && (GetRootporttoSetResourcesforTbt(&SetupData,RpIndex))) {
    if (!EFI_ERROR(Status)) {
      RsvdExtraBusNum = SetupData.TbtPcieExtraBusRsvd;
      RsvdPcieMegaMem = SetupData.TbtPcieMemRsvd;
      PcieMemAddrRngMax = SetupData.TbtPcieMemAddrRngMax;
      RsvdPciePMegaMem = SetupData.TbtPciePMemRsvd;
      PciePMemAddrRngMax = SetupData.TbtPciePMemAddrRngMax;
      RsvdPcieKiloIo = SetupData.TbtPcieIoRsvd;
    }
    SetResourceforTbt  = TRUE;
  } else {
    if (RpDev == SA_PEG_DEV_NUM) {
      if (!EFI_ERROR(Status2)) {
        // PEG
        RsvdExtraBusNum = SaSetup.PegExtraBusRsvd[RpIndex - PCIE_NUM];
        RsvdPcieMegaMem = SaSetup.PegMemRsvd[RpIndex - PCIE_NUM];
        RsvdPcieKiloIo = SaSetup.PegIoRsvd[RpIndex - PCIE_NUM];
      }
    } else {
      if (!EFI_ERROR(Status3)) {
        // PCH
        RsvdExtraBusNum = PchSetup.PcieExtraBusRsvd[RpIndex];
        RsvdPcieMegaMem = PchSetup.PcieMemRsvd[RpIndex];
        RsvdPcieKiloIo  = PchSetup.PcieIoRsvd[RpIndex];
      }
    }
  }

  //
  // Padding for bus
  //
  ZeroMem (PaddingResource, PADDING_NUM * sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR));
  *Attributes                   = EfiPaddingPciBus;

  PaddingResource->Desc         = 0x8A;
  PaddingResource->Len          = 0x2B;
  PaddingResource->ResType      = ACPI_ADDRESS_SPACE_TYPE_BUS;
  PaddingResource->GenFlag      = 0x0;
  PaddingResource->SpecificFlag = 0;
  PaddingResource->AddrRangeMin = 0;
  PaddingResource->AddrRangeMax = 0;
  PaddingResource->AddrLen      = RsvdExtraBusNum;

  //
  // Padding for non-prefetchable memory
  //
  PaddingResource++;
  PaddingResource->Desc                 = 0x8A;
  PaddingResource->Len                  = 0x2B;
  PaddingResource->ResType              = ACPI_ADDRESS_SPACE_TYPE_MEM;
  PaddingResource->GenFlag              = 0x0;
    if (SetResourceforTbt) {
    PaddingResource->AddrSpaceGranularity = 64;
  } else {
    PaddingResource->AddrSpaceGranularity = 32;
  }
  PaddingResource->SpecificFlag         = 0;
  //
  // Pad non-prefetchable
  //
  PaddingResource->AddrRangeMin = 0;
  PaddingResource->AddrLen      = RsvdPcieMegaMem * 0x100000;
  if (SetResourceforTbt) {
    PaddingResource->AddrRangeMax = (1 << PcieMemAddrRngMax) - 1;
  } else {
    PaddingResource->AddrRangeMax = 1;
  }

  //
  // Padding for prefetchable memory
  //
  PaddingResource++;
  PaddingResource->Desc                 = 0x8A;
  PaddingResource->Len                  = 0x2B;
  PaddingResource->ResType              = ACPI_ADDRESS_SPACE_TYPE_MEM;
  PaddingResource->GenFlag              = 0x0;
    if (SetResourceforTbt) {
    PaddingResource->AddrSpaceGranularity = 64;
  } else {
    PaddingResource->AddrSpaceGranularity = 32;
  }
  PaddingResource->SpecificFlag         = 06;
  //
  // Padding for prefetchable memory
  //
  PaddingResource->AddrRangeMin = 0;
  if (SetResourceforTbt) {
    PaddingResource->AddrLen      = RsvdPciePMegaMem * 0x100000;
  } else {
    PaddingResource->AddrLen      = RsvdPcieMegaMem * 0x100000;
  }
  //
  // Pad 16 MB of MEM
  //
  if (SetResourceforTbt) {
    PaddingResource->AddrRangeMax = (1 << PciePMemAddrRngMax) - 1;
  } else {
    PaddingResource->AddrRangeMax = 1;
  }
  //
  // Alignment
  //
  // Padding for I/O
  //
  PaddingResource++;
  PaddingResource->Desc         = 0x8A;
  PaddingResource->Len          = 0x2B;
  PaddingResource->ResType      = ACPI_ADDRESS_SPACE_TYPE_IO;
  PaddingResource->GenFlag      = 0x0;
  PaddingResource->SpecificFlag = 0;
  PaddingResource->AddrRangeMin = 0;
  PaddingResource->AddrLen      = RsvdPcieKiloIo * 0x400;
  //
  // Pad 4K of IO
  //
  PaddingResource->AddrRangeMax = 1;
  //
  // Alignment
  //
  // Terminate the entries.
  //
  PaddingResource++;
  ((EFI_ACPI_END_TAG_DESCRIPTOR *) PaddingResource)->Desc     = ACPI_END_TAG_DESCRIPTOR;
  ((EFI_ACPI_END_TAG_DESCRIPTOR *) PaddingResource)->Checksum = 0x0;

  *HpcState = EFI_HPC_STATE_INITIALIZED | EFI_HPC_STATE_ENABLED;

  return EFI_SUCCESS;
}
